<?php

namespace app\channel\controller\api;
use app\channel\ApiController;

use app\channel\model\ContractModel;
use app\channel\model\ProxyUsersModel;
use app\channel\model\ProxyLevelModel;
use app\channel\model\ProxyUpapplyLogModel;
use app\channel\model\RechargeLogModel;
use app\channel\model\WalletModel;
use app\mainadmin\model\PaymentModel;

/*------------------------------------------------------ */
//-- 代理会员相关API
/*------------------------------------------------------ */

class ProxyUsers extends ApiController
{
    /*------------------------------------------------------ */
    //-- 优先执行  当前由继承Users，$this->userInfo为会员
    /*------------------------------------------------------ */
    public function initialize()
    {
        parent::initialize();
        $this->Model = new ProxyUsersModel();
    }
    /*------------------------------------------------------ */
    //-- 获取登陆代理信息
    /*------------------------------------------------------ */
    public function getInfo()
    {
        $data['proxyInfo'] = $this->Model->info($this->userInfo['user_id']);
        //判断代理满足加入门槛
        $data['proxyInfo'] = $this->Model->joinCondition($data['proxyInfo']);
        return $this->success($data);
    }
    /*------------------------------------------------------ */
    //-- 获取登陆代理上级信息
    /*------------------------------------------------------ */
    public function getSuperiorInfo()
    {
        $proxyInfo = $this->Model->info($this->userInfo['user_id']);
        //推荐上级
        if ($proxyInfo['pid'] == 0){
            $data['parent_name'] = '厂家';
            $data['parent_level'] = '厂家';
            $data['parent_headimgurl'] = settings('logo');
            $data['parent_mobile'] = settings('channel_mobile');
            $data['parent_warrant_end_time'] = '--';
            $data['parent_reg_time'] = '--';
        }else{
            $parentUser = $this->Model->info($proxyInfo['pid']);
            $data['parent_name'] = $parentUser['byUser']['real_name'];
            $data['parent_headimgurl'] = $parentUser['byUser']['headimgurl'];
            $data['parent_mobile'] = $parentUser['byUser']['mobile'];
            $data['parent_level'] = $parentUser['proxyLevel']['proxy_name'];
            $data['parent_warrant_end_time'] = dateTpl($parentUser['warrant_end_time'],'Y-m-d H:i:s',true);
            $data['parent_reg_time'] = dateTpl($parentUser['reg_time'],'Y-m-d H:i:s',true);
        }
        //供货上级
        if ($this->userInfo['supply_uid'] == 0){
            $data['supply_name'] = '厂家';
            $data['supply_level'] = '厂家';
            $data['supply_headimgurl'] = settings('logo');
            $data['supply_mobile'] = settings('channel_mobile');
            $data['supply_warrant_end_time'] = '--';
            $data['supply_reg_time'] = '--';
        }else{
            $supplytUser = $this->Model->info($this->userInfo['supply_uid']);
            $data['supply_name'] = $supplytUser['byUser']['real_name'];
            $data['supply_headimgurl'] = $supplytUser['byUser']['headimgurl'];
            $data['supply_mobile'] = $supplytUser['byUser']['mobile'];
            $data['supply_level'] = $supplytUser['proxyLevel']['proxy_name'];
            $data['supply_warrant_end_time'] = dateTpl($supplytUser['warrant_end_time'],'Y-m-d H:i:s',true);
            $data['supply_reg_time'] = dateTpl($supplytUser['reg_time'],'Y-m-d H:i:s',true);
        }
        return $this->success($data);
    }



    /*------------------------------------------------------ */
    //-- 获取可邀请的代理层级
    /*------------------------------------------------------ */
    public function getInvitePorxyLevel(){
        $proxy_id = $this->Model->where('user_id',$this->userInfo['user_id'])->value('proxy_id');
        $data['proxyLevelList'] = (new ProxyLevelModel)->getInvitelist($proxy_id);
        return $this->success($data);
    }

    /*------------------------------------------------------ */
    //-- 获取邀请海报
    /*------------------------------------------------------ */
    public function getInvitePoster(){
        $proxy_id = input('proxy_id',0,'intval');
        $res = $this->Model->getInvitePoster($this->userInfo['user_id'],$proxy_id);
        if (is_array($res) == false){
            return $this->error($res);
        }
        return $this->success($res);
    }
    /*------------------------------------------------------ */
    //-- 获取可升级的层级
    /*------------------------------------------------------ */
    public function getUpgradeLevel(){
        $proxy_id = $this->Model->where('user_id',$this->userInfo['user_id'])->value('proxy_id');
        $data = (new ProxyLevelModel)->getUpgradeLevel($this->userInfo['user_id'],$proxy_id);
        unset($data['stepsList'][0]);
        return $this->success($data);
    }
    public function getProxyLevel(){
        $proxy_id = input('proxy_id','0','intval');
        if ($proxy_id < 1){
            return $this->error('传值错误.');
        }
        $proxyLevel = (new ProxyLevelModel())->info($proxy_id);

        return $this->success($proxyLevel);
    }
    /*------------------------------------------------------ */
    //-- 升级申请处理
    /*------------------------------------------------------ */
    public function appUpgrade(){
        $proxy_id = input('proxy_id','0','intval');
        if ($proxy_id < 1){
            return $this->error('传值错误.');
        }
        $ProxyLevelModel = new ProxyLevelModel();
        $res = $ProxyLevelModel->checkUpgrade($this->userInfo['user_id'],$proxy_id);
        if ($res !== true){
            return $this->error($res);
        }
        $proxyLevel = $ProxyLevelModel->info($proxy_id);
        if ($proxyLevel['is_auto_check'] == 0){ //非自动审核，写入申请记录
            $ProxyUpapplyLogModel = new ProxyUpapplyLogModel();
            $where[] = ['user_id','=',$this->userInfo['user_ud']];
            $where[] = ['status','=',0];
            $count = $ProxyUpapplyLogModel->where($where)->count();
            if ($count > 0){
                return $this->error('您已提交升级申请，正在审核中，不能重复提交.');
            }
            $ProxyUsersModel = new ProxyUsersModel();
            $inData['user_id'] = $this->userInfo['user_id'];
            $inData['proxy_id'] = $this->userInfo['proxy_id'];
            $inData['up_proxy_id'] = $proxy_id;
            $inData['pid'] = $this->userInfo['pid'];
            if ($inData['pid'] > 0){
                $pUserInfo = $ProxyUsersModel->info($inData['pid']);
                $inData['pid_proxy_id'] = $pUserInfo['proxy_id'];
            }
            $inData['supply_uid'] = $this->userInfo['supply_uid'];
            if ($inData['supply_uid'] > 0){
                $sUserInfo = $ProxyUsersModel->info($inData['pid']);
                $inData['supply_proxy_id'] = $sUserInfo['proxy_id'];
            }
            $inData['add_time'] = time();
            $res = $ProxyUpapplyLogModel->save($inData);
            if ($res < 1){
                return $this->error('录入升级申请失败，请重试.');
            }
            $msg = '提交成功，等待审核.';
        }else{//执行升级
            $res = $this->Model->upgrade($this->userInfo['user_id'],$proxy_id,'自动审核通过完成升级',$this);
            if ($res !== true){
                return $this->error($res);
            }
            $msg = '升级成功.';
        }
        return $this->success($msg);
    }


    /*------------------------------------------------------ */
    //-- 点击升级
    /*------------------------------------------------------ */
    public function addOrder() {
        $replenish_money = input('replenish_money','','trim');
        $orderModel = new RechargeLogModel();
        $info = $orderModel->where(['user_id'=>$this->userInfo['user_id'],'status'=>'0'])->find();
        if ($info) {
            return $this->error('您已提交升级申请，正在审核中，不能重复提交.');
        }
        $ProxyLevelModel = new ProxyLevelModel();

        $levelList = $ProxyLevelModel->getList();
        $rows = array_reverse($levelList);//反转数组
        unset($rows[0]);
        $proxy_id = 0;
        $ProxyUsersModel = new ProxyUsersModel();
        $userinfo = $ProxyUsersModel->where('user_id',$info['user_id'])->find();
        foreach ($rows as $key=>$row) {
            if ($row['proxy_id'] < $userinfo['proxy_id']) {
                $proxy_id = $row['proxy_id'];
                break;
            }
        }
        $save_data = [
            'type'=>'earnestMoney',
            'user_id'=>$this->userInfo['user_id'],
            'user_pid'=>$this->userInfo['pid'],
            'order_sn'=>'wsrecharge'.time().rand(11,99),
            'order_amount'=>$replenish_money,
            'transaction_id'=>'',
            'pay_id'=>3,
            'pay_code'=>'offline',
            'pay_name'=>'线下打款',
            'imgs'=>'',
            'remark'=>'',
            'status'=>0,
            'check_remark'=>'',
            'add_time'=>time(),
            'pay_time'=>time(),
            'check_time'=>0,
            'admin_id'=>0,
            'is_reward'=>0,
            'supply_uid'=>0,
            'proxy_id'=>$proxy_id,
            'upgrade_type'=>1,
            'supply_uid'=>$this->userInfo['supply_uid']
        ];
        if($orderModel->save($save_data)) {
            return $this->success('提交成功.');
        } else {
            return $this->error('提交失败.');
        }
    }

    /**
     * 获取用户签约合同
     */
    public function getContract(){
        $proxy_id = input('proxy_id','0','intval');
        if ($proxy_id < 1){
            return $this->error('传值错误.');
        }
        $contract = (new ContractModel())->getContractByUserIdAndProxyId($this->userInfo['user_id'], $proxy_id);
        $data['contract'] = $contract;
        return $this->success($data);
    }

    /**
     * 获取合同
     */
    public function getContractInfo(){
        $proxy_id = input('proxy_id','0','intval');
        if ($proxy_id < 1){
            return $this->error('传值错误.');
        }
        $proxy_contract = (new ProxyLevelModel())->info($proxy_id);
        $contract = (new ContractModel())->getContractByUserIdAndProxyId($this->userInfo['user_id'], $proxy_id);
        if (empty($contract)){
            $contract['is_signature'] = 0;
        }
        $data['user_contract'] = $contract;
        $data['proxy_contract'] = $proxy_contract;
        return $this->success($data);
    }

    public function saveContract(){
        $proxy_id = input('proxy_id','0','intval');
        $upgrade_type = input('upgrade_type','0','intval');
        $sign_img = input('sign_img');
        if ($proxy_id < 1){
            return $this->error('传值错误.');
        }
        $extend = getFileExtend($sign_img);
        if ($extend == false){
            return $this->error('未能识别签名，请重新签名.');
        }

        $file_path = config('config._upload_') . 'contract/' . $this->userInfo['user_id'] . '/';
        $file_name = $this->userInfo['user_id'] . '_' . $proxy_id .'.'.$extend[1];
        $res = base64ToImage($sign_img, $file_path, $file_name);
        if ($res == false){
            return $this->error('头像保存失败，请重试.');
        }

        $data['sign_img'] = trim($file_path . $file_name, '.');

        $contractModel = new ContractModel();

        $contract = $contractModel->getContractByUserIdAndProxyId($this->userInfo['user_id'], $proxy_id);

        if (empty($contract)){
            $data['sign_time'] = time();
        }else{
            $data['sign_time'] = $contract['sign_time'];
            $data['update_time'] = time();
            $contractModel = $contract;
        }
        $data['is_signature'] = 1;
        $data['proxy_id'] = $proxy_id;
        $data['user_id'] = $this->userInfo['user_id'];

        if($contractModel->save($data)) {

            if ($upgrade_type == 1){
                $this->saveRecharge($proxy_id);
            }

            return $this->success('保存成功.');
        } else {
            return $this->error('保存失败.');
        }

    }

    /**
     * 获取最新一条升级申请
     */
    public function getApplyInfo(){
        $proxy_id = input('proxy_id','0','intval');
        $upgrade_type = input('upgrade_type',1,'intval');
        if ($proxy_id < 1){
            return $this->error('传值错误.');
        }
        $info = (new RechargeLogModel())->getLastOne($this->userInfo['user_id'], $proxy_id, $upgrade_type);
        if (!empty($info)){
            switch ($info['status']){
                case 0:
                    $info['status_txt'] = '审核中';
                    $info['status_img'] = 1;
                    break;
                case 1:
                    $info['status_txt'] = '审核失败';
                    $info['status_img'] = 12;
                    break;
                case 9:
                    $info['status_txt'] = '升级成功';
                    $info['status_img'] = 55;
                    break;
                default:
                $info['status_txt'] = '';
                $info['status_img'] = 0;
            }
            $info['add_time'] = date('Y-m-d H:i:s', $info['add_time']);
        }
        $data['info'] = $info;
        $data['proxy_info'] = (new ProxyLevelModel())->info($proxy_id);
        return $this->success($data);
    }

    public function setUserCheck(){
        $id = input('id','0','intval');
        if ($id < 1){
            return $this->error('传值错误.');
        }

        (new RechargeLogModel())->where('order_id', $id)->update(['user_check' => 1]);
        return $this->success('ok');
    }

    /**
     * 业绩升级申请
     * @param $proxy_id
     * @param $upgrade_type
     */
    private function saveRecharge($proxy_id)
    {

        $remark = input('remark', '', 'trim');

        $money = 0;
        $type = 'earnestMoney';
        $payInfo = [
            'pay_id' => 0,
            'pay_name' => '业绩升级'
        ];
        $payCode = '';
        $fileList = '';
        $upgrade_type = 1;
        $order_type = 1;

        $order_id = (new WalletModel())->saveRecharge($money, $type, $remark, $payInfo, $payCode, $fileList, $proxy_id, $upgrade_type, $order_type);
        if (is_numeric($order_id) == false) {
            return $this->error($order_id);
        }
        $data['order_id'] = $order_id;
        return $this->success($data);
    }

}
